package com.zazu.mycl.application;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

import com.zazu.mycl.application.terminal.*;
import com.zazu.mycl.application.*;

/**
 * 
 *
 * @author Zazu (Zach Zurn)
 *
 */
public class ApplicationController {

	public static void main(String[] args)
	{
		startApp();
	}
	
	public static Document getCommandMappings()
	{
		ApplicationController.logger.log(Level.INFO,"Reading in mappings.");
		
		try {
		
			InputStream stream = DefaultCommandRunner.class.getResourceAsStream("resources/mappings.xml");
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			mappings = builder.parse(stream);
			
			return mappings;
			
		} catch (Exception e) {
			ApplicationController.logger.log(Level.ALL,"Unable to read mappings file...");
			return null;
		}
		
	}
	
	private static void startApp()
	{
		Handler handler;
		try {
			logger.setLevel(Level.ALL);
			final int LOG_ROTATION_COUNT = 10;
			handler = new FileHandler("%h/mycl.log",0,LOG_ROTATION_COUNT);
			logger.addHandler(handler);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			logger.log(Level.SEVERE, "Cannot instantiate log file handler.");
		}
		
		logger.log(Level.INFO, "Application initialized.");
		
		addTerminal();
		//addTerminal();
		
	}
	
	public static void addTerminal()
	{
		MyClWindow newTerminal = new MyClWindow();
		newTerminal.init();
		Terminals.add(newTerminal);
		
		logger.log(Level.INFO, "Terminal window added. Window ID: "+newTerminal.getwindowID());
	}
        
        public static void removeTerminal(int terminalID)
        {
                MyClWindow windowClose = Terminals.get(terminalID);
                //Might need fixing to remove the window from memory
                windowClose.dispose();
        }
	
	
	public static final Logger logger = Logger.getLogger("com.zazu.mycl");
	private static List<MyClWindow> Terminals = new ArrayList<MyClWindow>();
	private static Document mappings;
}
